﻿/*
 * Cratos Desktop
 * Cratos Dual WCF Service class
 * 
 * Copyright (c) 2011 Draco
 * 
 * This file is part of Cratos.
 * 
 * Cratos is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Cratos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cratos.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *       .==.        .==.
 *      //'^\\      //^'\\
 *     // ^ ^\(\__/)/^ ^^\\
 *    //^ ^^ ^/6  6\ ^^ ^ \\
 *   //^ ^^ ^/( .. )\^ ^ ^ \\
 *  // ^^ ^/\| V""V|/\^ ^ ^ \\
 * //^^/\/ /  '~~'  \ \/\^ ^ \\
 *  ------------------------------------
 *  HERE BE DRAGONS
 *  
 *  Johan Dercksen - johan@draco.co.za
 */
using System;
using System.Text;
using System.Linq;
using System.ServiceModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Cratos.Tools.General;
using Cratos.Desktop.CratosDualWcfService;

namespace Cratos.Desktop
{
	/// <summary>
	/// Cratos WCF Static class
	/// </summary>
	public class CDualWcfService
	{
		#region Class Constant declarations
		#endregion

		#region Class Event declarations
		/// <summary>
		/// Web Service online event
		/// </summary>
		public static event ServerStateEventHandler WebServiceOnline;

		/// <summary>
		/// Web Service offline event
		/// </summary>
		public static event ServerStateEventHandler WebServiceOffline;

		/// <summary>
		/// Cratos New Page Event
		/// </summary>
		public event CratosNewPageEventHandler NewPage;

		/// <summary>
		/// Cratos Error Event
		/// </summary>
		public event CratosErrorEventHandler Error;

		/// <summary>
		/// Cratos Completed Event
		/// </summary>
		public event CratosCompletedEventHandler Completed;
		#endregion

		#region Class Variable declarations
		private static bool		isUrlChanged   = true;
		private static Uri		wcfServiceUri;
		private static string connectionName = "CratosDB";
		#endregion

		#region Class Constructors & Destructors
		/// <summary>
		/// Class Constructor
		/// </summary>
		public CDualWcfService()
		{
			// Create and Setup the WCF Service
			this.SetupWcfService();
		}
		#endregion

		#region Class Properties
		/// <summary>
		/// WCF Service URI
		/// </summary>
		public static Uri WcfServiceUri
		{
			get { return (wcfServiceUri); }
			set { wcfServiceUri = value; isUrlChanged = true; }
		}

		/// <summary>
		/// Database Connection Name
		/// </summary>
		public static string ConnectionName
		{
			get { return (connectionName); }
			set { connectionName = value; }
		}

		/// <summary>
		/// WCF Service
		/// </summary>
		public CratosDualWcfServiceClient WcfService { get; set; }

		/// <summary>
		/// WCF Service Callback
		/// </summary>
		public CratosDualWcfServiceCallback WcfServiceCallback { get; set; }
		#endregion

		#region Class Methods
		/// <summary>
		/// Determine if the Web Service is available or not
		/// </summary>
		/// <returns>
		/// A boolean is returned indicating the success of the method
		/// </returns>
		public bool Ping()
		{
			// Declare the required variables
			bool returnValue = false;

			try
			{
				// Create and Setup the object if required
				if ((this.WcfService == null) || (isUrlChanged)) { this.SetupWcfService(); }

				// Ping the Web Service
				returnValue = this.WcfService.Ping();

				// Raise the Wb Service Online event
				OnWebServiceOnline();
			}
			catch (Exception runtimeException)
			{
				// Display the error message
				CratosHelper.LogMessage(CratosLogSeverity.Exception, "Cratos Proxy", "Runtime exception occurred", runtimeException, false);

				// Raise the offline event
				OnWebServiceOffline();
			}

			// Return to calling method
			return (returnValue);
		}

		/// <summary>
		/// Perform the Web Service action
		/// </summary>
		/// <param name="ctCratos">Cratos contract containing the relevant request information</param>
		/// <returns>Cratos contract containing the relevant response information</returns>
		public bool PerformAction(CratosWcfContract ctCratos)
		{
			// Declare the required variables
			bool returnValue = false;

			try
			{
				// Create and Setup the object if required
				if ((this.WcfService == null) || (isUrlChanged)) { this.SetupWcfService(); }

				// Make a call to the Web Service
				returnValue = this.WcfService.CratosPerformAction(ctCratos);
			}
			catch (Exception runtimeException)
			{
				// Determine if the WS is available
				if (Ping()) { throw new Exception(runtimeException.Message, runtimeException.InnerException); }
				else
				{
					ctCratos.Errors = new string[] 
			                  {
			                    string.Format("[{0} - {1}] [{2}] {3}\n{4}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
			                                                           "Cratos Dual WCF Service",
			                                                           CratosLogSeverity.Exception,
			                                                           "Server Unavailable", runtimeException.ToString())
			                  };
				}
			}

			// Return to calling method
			return (returnValue);
		}
		#endregion

		#region Class Support Methods
		private void SetupWcfService()
		{
			// Declare the required v ariables

			// Create a new Callback Context
			this.WcfServiceCallback            = new CratosDualWcfServiceCallback();
			this.WcfServiceCallback.NewPage   += new CratosNewPageEventHandler(this.OnCratosDualWcfServiceCallbackNewPage);
			this.WcfServiceCallback.Error     += new CratosErrorEventHandler(this.OnCratosDualWcfServiceCallbackError);
			this.WcfServiceCallback.Completed += new CratosCompletedEventHandler(this.OnCratosDualWcfServiceCallbackCompleted);

			// Create and Setup the WCF Service
			this.WcfService                  = new CratosDualWcfServiceClient(new InstanceContext(this.WcfServiceCallback));
			this.WcfService.Endpoint.Address = new EndpointAddress(CDualWcfService.WcfServiceUri);

			// Reset the Changed URL indicator
			CDualWcfService.isUrlChanged = false;

			// Return to calling method
			return;
		}

		private static void OnWebServiceOnline()
		{
			// Raise the event if required
			if (WebServiceOnline != null) { WebServiceOnline(); };
		}

		private static void OnWebServiceOffline()
		{
			// Raise the event if required
			if (WebServiceOffline != null) { WebServiceOffline(); }
		}

		private void OnCratosDualWcfServiceCallbackNewPage(long pageNo, Collection<IDOCratos> doCollection)
		{
			// Declare the required variables

			// Raise the relevant event if required
			if (this.NewPage != null) { this.NewPage(pageNo, doCollection); }

			// Return to calling method
			return;
		}

		private void OnCratosDualWcfServiceCallbackError(Collection<CratosError> errorCollection)
		{
			// Declare the required variables

			// Raise the relevant event if required
			if (this.Error != null) { this.Error(errorCollection); }

			// Return to calling method
			return;
		}

		private void OnCratosDualWcfServiceCallbackCompleted(DOCratosActionResult actionResult, Collection<IDOCratos> doCollection)
		{
			// Declare the required variables

			// Raise the relevant event if required
			if (this.Completed != null) { this.Completed(actionResult, doCollection); }

			// Return to calling method
			return;
		}
		#endregion
	}
}
